package com.sdk.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coment.dto.ApiNotify;
import com.sdk.apiNotify.rabbitmq.producer.ApiNotifyProducer;
import com.sdk.ks.KSServiceImpl;
import com.sdk.service.impl.DYServiceImpl;
import com.sdk.utill.DYUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(
   value = {"/${spring.application.name}"},
   name = "api"
)
public class ApiController {
   @Resource
   private DYServiceImpl dyService;
   @Resource
   private KSServiceImpl ksService;
   @Resource
   private ApiNotifyProducer apiNotifyProducer;

   @PostMapping({"/douyin-notify"})
   public void handler(
           @RequestHeader("x-roomid") String roomId,
           @RequestHeader("x-msg-type") String msgType,
           @RequestBody String requestBody,
           HttpServletResponse response
   ) throws IOException {
      try {
         for(ApiNotify apiNotify : this.dyService.parseDouyin(roomId, msgType, requestBody)) {
            this.apiNotifyProducer.sendMessage(apiNotify);
         }
      } catch (Exception e) {
         log.error("解析抖音传输过来的消息失败:", e);
      }

      response.setStatus(200);
      response.setContentType("text/html;charset=utf-8");
      response.getWriter().close();
   }

   private String setNotify(String requestBody) {
      Map<String, Object> map = new HashMap<>();

      try {
         for(ApiNotify apiNotify : this.ksService.parseKuaishou(requestBody)) {
            this.apiNotifyProducer.sendMessage(apiNotify);
         }
      } catch (Exception e) {
         log.error("解析快手传输过来的消息失败:", e);
         map.put("result", 50);
         map.put("errorMsg", e.getMessage());
         return JSON.toJSONString(map);
      }

      map.put("result", 1);
      map.put("errorMsg", "");
      return JSON.toJSONString(map);
   }

   @PostMapping({"/douyin/round/query_user_camp_data"})
   public Object queryViewerCampData(@RequestBody String requestBody, HttpServletRequest request) {
      Map<String, Object> res = new HashMap<>();
      Map<String, String> header = new HashMap<>();
      long timestamp = Long.parseLong(request.getHeader("x-timestamp"));
      header.put("x-nonce-str", request.getHeader("x-nonce-str"));
      header.put("x-timestamp", "" + timestamp);
      header.put("x-roomid", request.getHeader("x-roomid"));
      header.put("x-msg-type", request.getHeader("x-msg-type"));
      String signatureStr = request.getHeader("x-signature");

      try {
         String signature = DYUtil.signature(header, requestBody);
         if (signature == null || !signature.equals(signatureStr) || System.currentTimeMillis() - timestamp > 20L) {
            log.error("签名错误");
            res.put("errmsg", "签名错误");
            res.put("errcode", 40004);
         }
      } catch (Exception var13) {
         log.error("签名错误");
         res.put("errmsg", "签名错误");
         res.put("errcode", 40004);
      }

      try {
         JSONObject jsonObject = JSON.parseObject(requestBody);
         String appId = jsonObject.getString("app_id");
         String uId = jsonObject.getString("open_id");
         String roomId = jsonObject.getString("room_id");
         res.put("errcode", 0);
         res.put("errmsg", "success");
      } catch (Exception var12) {
         log.error("房间id、小玩法app_id等入参解析失败，检查参数解析逻辑");
         res.put("errcode", 40001);
      }

      return res;
   }

   @PostMapping({"/douyin/user_choose_camp"})
   public Object chooseViewerCamp(@RequestBody String requestBody, HttpServletRequest request) {
      Map<String, Object> res = new HashMap();
      Map<String, String> header = new HashMap();
      long timestamp = Long.parseLong(request.getHeader("x-timestamp"));
      header.put("x-nonce-str", request.getHeader("x-nonce-str"));
      header.put("x-timestamp", "" + timestamp);
      header.put("x-roomid", request.getHeader("x-roomid"));
      header.put("x-msg-type", request.getHeader("x-msg-type"));
      String signatureStr = request.getHeader("x-signature");

      try {
         String signature = DYUtil.signature(header, requestBody);
         if (signature == null || !signature.equals(signatureStr) || System.currentTimeMillis() - timestamp > 5000L) {
            log.error("签名错误");
            res.put("errmsg", "签名错误");
            res.put("errcode", 40004);
         }
      } catch (Exception var16) {
         log.error("签名错误");
         res.put("errmsg", "签名错误");
         res.put("errcode", 40004);
      }

      try {
         JSONObject jsonObject = JSON.parseObject(requestBody);
         String appId = jsonObject.getString("app_id");
         String uId = jsonObject.getString("open_id");
         String roomId = jsonObject.getString("room_id");
         String groupId = jsonObject.getString("group_id");
         String avatarUrl = jsonObject.getString("avatar_url");
         String nickname = jsonObject.getString("nickname");
         res.put("errcode", 0);
         res.put("errmsg", "success");
      } catch (Exception var15) {
         log.error("房间id、小玩法app_id等入参解析失败，检查参数解析逻辑");
         res.put("errcode", 40001);
      }

      return res;
   }

   @PostMapping({"/kuaishou-notify/{type}"})
   public String KuaiShouHandler(
           @RequestBody String requestBody,
           @PathVariable String type
   ) throws IOException {
//      log.info("接收到快手消息:{}--{}", type , requestBody);
      log.info("接收到快手消息:{}",  requestBody);
      return this.setNotify(requestBody);
   }

   @PostMapping({"/kuaishou-notify/like"})
   public String KuaiShouHandler2(@RequestBody String requestBody) throws IOException {
      return this.setNotify(requestBody);
   }

   @PostMapping({"/kuaishou-notify/content"})
   public String KuaiShouHandler3(@RequestBody String requestBody) throws IOException {
      return this.setNotify(requestBody);
   }
}
